package com.crm.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.crm.entity.Userchecks;
import com.crm.service.UserChecksService;
import com.crm.utils.DateUtil;
import com.crm.utils.PageUtil;
import com.crm.utils.ResponeMessageUtil;
import com.crm.utils.UUIDUtil;

@RestController
@RequestMapping("/userChecks")
public class UserChecksController {

	@Autowired
	private UserChecksService userChecksService;

	/**
	 * 多条件查询考勤信息
	 * 
	 * @param limit
	 * @param page
	 * @param id
	 * @param username
	 * @param checkintime
	 * @param checkstate
	 * @param checkouttime
	 * @return
	 */
	@RequestMapping("/selectUserChecksAll")
	public ResponeMessageUtil selectUserChecksAll(Integer limit, Integer page, String username, String checkintime,
			String checkstate, String checkouttime) {
		int setValue = PageUtil.getSetValue(page, limit);
		return ResponeMessageUtil.ok(userChecksService.getCount(username, checkintime, checkstate, checkouttime),
				userChecksService.selectAll(setValue, limit, username, checkintime, checkstate, checkouttime));
	}

	/**
	 * 创建考勤信息
	 * 
	 * @param userchecks
	 * @return
	 */
	@RequestMapping("/insertSignIn")
	public boolean insertSignIn(Userchecks userchecks) {
		userchecks.setId(UUIDUtil.getUUID());
		userchecks.setCheckintime(DateUtil.dateToString(new Date()));
		userchecks.setCheckstate("1");
		return userChecksService.insert(userchecks) > 0 ? true : false;
	}

	/**
	 * 更新考勤信息
	 * 
	 * @param userchecks
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping("/updateSignIn")
	public boolean updateSignIn(Userchecks userchecks, String userid) throws ParseException {
		Userchecks selectTime = userChecksService.selectListAll(userid);
		String signInTime = selectTime.getCheckintime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date time1 = sdf.parse(signInTime);
		Calendar calendar = Calendar.getInstance();
		calendar.add(calendar.MINUTE, -10);
		Date time2 = calendar.getTime();
		if (time1.after(time2)) {
			return false;
		}
		userchecks.setCheckouttime(DateUtil.dateToString(new Date()));
		userchecks.setCheckstate("2");
		userChecksService.update(userchecks);
		return true;
	}

	/**
	 * 查询是否签到
	 * 
	 * @param userid
	 * @return
	 */
	@RequestMapping("/selectSignIn")
	public ResponeMessageUtil selectSignIn(String userid) {
		return ResponeMessageUtil.ok(userChecksService.selectListAll(userid) != null ? "success" : "error",
				userChecksService.selectListAll(userid));
	}

}
